import Vue from "vue"
import Toasts from './toast.vue';
const ToastConstructor = Vue.extend(Toasts);

let instance:any;
const instances:Array<any> = [];

const Toast = function(options:any):void {
  if (Vue.prototype.$isServer) return;
  options = options || {};
  if (typeof options === 'string') {
    options = {
      message: options
    };
  }
  instance = new ToastConstructor({
    data: options
  });
  instance.vm = instance.$mount();
  instance.vm.visible = true;
  document.body.appendChild(instance.vm.$el);
  instances.push(instance);
  return instance.vm;
};

['success', 'warning', 'info', 'error' , 'loading'].forEach(type => {
  Toast[type] = (options:any) => {
    if (typeof options === 'string') {
      options = {
        message: options
      };
    }
    options.type = type;
    return Toast(options);
  };
});

Toast.close = function() {
  for (let i = instances.length - 1; i >= 0; i--) {
    instances[i].close();
  }
};


export default Toast;
